package validation

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"mall_frontend_api/biz/lib/biz_error"
	"mall_frontend_api/biz/model"
	"mall_frontend_api/biz/model/user_address"
)

func CheckUpdateUserAddress(ctx context.Context, req *user_address.UpdateUserAddressRequest, userInfo *model.UserInfo) error {
	userAddressInfo, err := dao.UserAddressDAO.GetInfoByID(ctx, req.GetID())
	if err != nil {
		return biz_error.NewBizError().SetLogMessage("dal GetUserAddressInfoByID").SetServerErrorMessage(err.Error())
	}

	if userAddressInfo.UserID != userInfo.ID {
		return biz_error.NewBizError().SetLogMessage("userInfo not match").SetServerErrorMessage("Authentication failed")
	}

	return nil
}

func CheckDeleteUserAddress(ctx context.Context, req *user_address.DeleteUserAddressRequest, userInfo *model.UserInfo) error {
	userAddressMap, err := dao.UserAddressDAO.MGet(ctx, req.GetIDs())
	if err != nil {
		return biz_error.NewBizError().SetLogMessage("dal GetCartInfoByID").SetServerErrorMessage(err.Error())
	}

	if len(userAddressMap) != len(req.GetIDs()) {
		return biz_error.NewBizError().SetLogMessage("dal 数量不匹配").SetServerErrorMessage("Authentication failed")
	}

	for _, c := range userAddressMap {
		if c.UserID != userInfo.ID {
			return biz_error.NewBizError().SetLogMessage("userInfo not match").SetServerErrorMessage("Authentication failed")
		}
	}

	return nil
}

func CheckSetDefaultUserAddress(ctx context.Context, req *user_address.SetDefaultUserAddressRequest, userInfo *model.UserInfo) (*model.UserAddress, error) {
	userAddress, err := dao.UserAddressDAO.GetInfoByID(ctx, req.GetID())
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, biz_error.NewBizError().SetLogMessage("dal GetCartInfoByID").SetServerErrorMessage(err.Error())
	}

	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, biz_error.NewBizError().SetLogMessage("dal 数量不匹配").SetServerErrorMessage("Authentication failed")
	}

	if userAddress.UserID != userInfo.ID {
		return nil, biz_error.NewBizError().SetLogMessage("userInfo not match").SetServerErrorMessage("Authentication failed")
	}

	return userAddress, nil
}
